<?php

namespace App\Admin\Controllers;

use App\Models\Order;
use App\Models\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;

class OrderController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = 'Order';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Order());

        $grid->column('id', __('Id'));
        $grid->column('order_sn', __('订单号'));
        $grid->column('goods_id', __('商品id'));
        $grid->column('price', __('价格'));
        $grid->column('uid', __('买家id'));
        $grid->column('sale_id', __('卖家id'));
        $grid->column('status', __('状态'))->using([1=>'已下单',2=>'已付款',3=>'卖家已发货',4=>'买家确认收货']);
        $grid->column('created_at', __('创建时间'));
        $grid->column('updated_at', __('最后更新时间'));

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Order::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('order_sn', __('Order sn'));
        $show->field('goods_id', __('Goods id'));
        $show->field('price', __('价格'));
        $show->field('status', __('状态'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));
        $show->field('deleted_at', __('Deleted at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Order());

        $form->text('order_sn', __('订单号'))->disable();
        $form->number('goods_id', __('Goods id'))->disable();
        $form->decimal('price', __('Price'));
        $form->number('uid', __('Uid'));
        $form->number('sale_id', __('Sale id'));
        $form->select('status', __('状态'))->options([1=>'已下单',2=>'已付款',3=>'卖家已发货',4=>'买家确认收货']);

        $form->saved(function (Form $form) {
            if($form->status == 4){
                User::where('id',$form->sale_id)->increment('money',$form->price);
            }
        });
        return $form;
    }
}
